<template>
  <Modal
    v-model="show"
    v-bind:title="modalTitle"
    :scrollable="true"
    class-name="vertical-center-modal"
    :mask-closable="false"
    @on-cancel="cancel"
  >
    <Form ref="selectionForm" :label-width="80" :model="info" :rules="ruleValidate">
      <FormItem label="截图" prop="capture">
        <a href="javascript:;" class="image-file" ref="feature_pic"></a>
      </FormItem>
      <FormItem label="姓名" prop="user_name">
        <Input
          v-model.trim="info.user_name"
          placeholder="请填写姓名"
          :search="true"
          @on-change="handleSearch"
          icon="ios-search-strong"
        />
      </FormItem>
      <FormItem label="选择" prop="select_row">
        <Table
          :highlight-row="true"
          height="200"
          :loading="loading"
          :columns="userColumns"
          :data="userData"
          :show-header="false"
          @on-current-change="changeSelection"
        ></Table>
      </FormItem>
    </Form>
    <div slot="footer">
      <Button type="primary" @click="handleSubmit" :disabled="disabled">提交</Button>
    </div>
  </Modal>
</template>
<script>
import { getTypeList } from "../../../controllers/record";
import {
  getStaffData,
  getAvatar,
  addOrUpdateGuest,
  deleteUser,
  getDepartmentList,
  regFeature,
  getFeature,
  delFeature,
  uploadStaffData,
  registBatch,
  getGuestData,
  getVipData,
  mergeFeature,
  addFeature
} from "../../../controllers/user";
import Constant from "../../../libs/constants";
import fakeAvatar from "../../../images/default_avatar.png";
import pic from "../../../images/upload.png";
import { read, recordToUser } from "../../../controllers/record";

export default {
  name: "merge-to",
  data: () => {
    return {
      show: false,
      modalTitle: "合并特征至现有人员",
      typeList: [],
      loading: false,
      disabled: true,
      from_id: "",
      to_id: "",
      rec_id: "",
      info: {
        user_id: "",
        user_type: "0",
        user_name: ""
      },
      userData: [],
      rec_capture: "",
      userColumns: [
        {
          title: "头像",
          align: "center",
          key: "user_avatar",
          render: (h, { row, column, index }) => {
            //拼装url
            let imgSrc = fakeAvatar;
            let encode = row[column.key];
            if (encode) {
              imgSrc = encode;
            }
            return (
              <div>
                <img class="user-avatar" alt="头像" src={imgSrc} />
              </div>
            );
          }
        },
        {
          title: "姓名",
          align: "center",
          key: "user_name"
        },
        {
          title: "类型",
          align: "center",
          key: "user_type_disp"
        }
      ],
      ruleValidate: {}
    };
  },
  created() {
    this.loadData();
  },
  methods: {
    loadData() {
      this.loading = true;
      return Promise.all([
        getGuestData(1, Constant.PAGE_SIZE, this.info.user_name),
        getStaffData(1, Constant.PAGE_SIZE, this.info.user_name),
        getVipData(1, Constant.PAGE_SIZE, this.info.user_name)
      ]).then(list => {
        this.loading = false;
        this.data = this.formatData(list[0])
          .concat(this.formatData(list[1]))
          .concat(this.formatData(list[2]));
        this.search();
      });
    },
    formatData(json) {
      //检测状态码
      if (json.code !== 0) {
        //非正常就返回空表
        return [];
      }
      let data = json.data;
      //检测数据块存在及长度
      if (data === undefined) {
        return [];
      }

      let { total, result } = data;

      // _.map(result, v => ({
      //     user_id: v["user_id"],
      //     user_name: v["user_name"],
      //     user_type: v["user_type"],
      //     user_type_disp: v["user_type_disp"],
      //     user_avatar: v["user_avatar"], //to-do:缺占位图base64
      //     user_picReg: [],
      //     user_sex: v["user_sex"] === 0 ? "0" : "1",
      //     user_phone: v["user_phone"],
      //     access_from: v["access_from"] || "",
      //     access_to: v["access_to"] || "",
      //     user_mark: v["user_mark"] || "",
      //     user_company: v["user_company"] || "",
      //     user_receptionist: v["user_receptionist"] || "",
      // }))
      let temp = _.map(result, v => ({
        user_id: v["user_id"],
        user_type: v["user_type"],
        user_type_disp: v["user_type_disp"] ? v["user_type_disp"] : "正式员工",
        user_name: v["user_name"],
        employee: v["user_type"] > 0 ? true : false,
        department: v["user_dept"],
        user_dept_disp: v["user_dept_disp"],
        employedTime: v["c_at"] || "无数据",
        avatarDis: v["user_avatar"], //to-do:缺占位图base64
        user_avatar: v["user_avatar"],
        avatarReg: [],
        user_no: v["user_no"],
        user_phone: v["user_phone"],
        user_email: v["user_email"],
        user_position: v["user_position"],
        access_from: v["access_from"],
        access_to: v["access_to"],
        user_sex: v["user_sex"] === 0 ? "0" : "1",
        user_mark: v["user_mark"]
      }));
      return temp;
    },
    showModal(row) {
      let img = pic;
      if (row.user_avatar) {
        img = row.user_avatar;
      }
      if (row.rec_capture) {
        img = row.rec_capture;
        this.rec_capture = row.rec_capture;
      }
      this.$refs["feature_pic"].style.backgroundImage = "url(" + img + ")";
      this.from_id = row.user_id;
      this.rec_id = row.rec_id;
      this.loadData().then(() => {
        this.show = true;
      });
    },
    cancel() {
      this.show = false;
    },
    handleSearch() {
      // this.search();
      this.loadData();
    },
    search() {
      let data = [];
      let name = this.info.user_name;
      this.disabled = true;
      this.data.map(item => {
        if (item.user_name.indexOf(name) >= 0) {
          data.push(item);
        }
      });
      this.userData = data;
    },
    async handleSubmit() {
      if (this.from_id) {
        mergeFeature(this.from_id, this.to_id).then(res => {
          if (res.code == 0) {
            this.$Message.success("提交成功!");
            this.show = false;
            this.$emit("updated");
          } else {
            this.$Message.error("提交失败!");
          }
        });
      } else {
        let image = await read(this.rec_capture);
        let parts = image.split(",");
        let format = parts[0];
        let data = parts[1];
        addFeature({
          user_id: this.to_id,
          feature_pic: [
            {
              type: "png",
              picdata: data
            }
          ]
        }).then(res => {
          if (res.code == 0) {
            this.$Message.success("提交成功!");
            this.show = false;
            this.$emit("updated");
          } else {
            this.$Message.error("提交失败!");
          }
        });
        recordToUser({
          rec_id: this.rec_id,
          user_id: this.to_id
        });
      }
    },
    changeSelection(row) {
      console.log(row);
      this.to_id = row.user_id;
      this.disabled = false;
    },
    preview() {}
    // cancelSelection(selection) {
    //   console.log(selection);
    // }
  }
};
</script>
<style scoped lang="less">
.image-file {
  position: relative;
  display: inline-block;
  background: url("../../../images/upload.png");
  background-size: 110px 110px;
  border: 1px solid #cfcfcf;
  //border-radius: 5%;
  //padding: 4px 12px;
  width: 110px;
  height: 110px;
  overflow: hidden;
  color: #1e88c7;
  text-decoration: none;
  text-indent: 0;
  line-height: 20px;
  input {
    position: absolute;
    font-size: 100px;
    width: 110px;
    height: 110px;
    right: 0;
    top: 0;
    opacity: 0;
  }
  :hover {
    background: #aadffd;
    border-color: #78c3f3;
    color: #004974;
    text-decoration: none;
  }
}
</style>